package com.roubsite.cloud.common.db.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.roubsite.cloud.common.db.multiple.MultipleDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyBatiesConfiguration {
	Logger logger = LoggerFactory.getLogger(MyBatiesConfiguration.class);
	@Autowired
	private DataSourceProperties dsList;

	public DruidDataSource getDataSource(DataSourceConfig druidConfigBean) {
		DruidDataSource druidDataSource = new DruidDataSource();
		druidDataSource.setDriverClassName(druidConfigBean.getDriverClassName());
		druidDataSource.setUsername(druidConfigBean.getUsername());// 用户名
		druidDataSource.setPassword(druidConfigBean.getPassword());// 密码
		druidDataSource.setUrl(druidConfigBean.getUrl());// 链接字符串
		druidDataSource.setInitialSize(druidConfigBean.getInitialSize());// 初始化连接数
		druidDataSource.setMinIdle(-1);
		druidDataSource.setMaxActive(druidConfigBean.getMaxActive());// 最大连接数
		// 链接保持
		druidDataSource.setKeepAlive(druidConfigBean.isKeepAlive());
		druidDataSource.setMaxWait(druidConfigBean.getMaxWaitMillis());// 最大等待时间
		druidDataSource.setMaxWaitThreadCount(druidConfigBean.getMaxWaitThreadCount());// 最大等待线程数，当超过这个数量的线程在等待时，新的请求将直接返回超时
		try {
			druidDataSource.setFilters("stat");
		} catch (SQLException e) {
		}
		druidDataSource.setTestOnBorrow(true);
		druidDataSource.setPoolPreparedStatements(false);
		druidDataSource.setRemoveAbandoned(true);// 超过时间限制是否回收
		druidDataSource.setRemoveAbandonedTimeout(600);// 超时时间；单位为秒。180秒=3分钟
		druidDataSource.setLogAbandoned(false);
		try {
			druidDataSource.init();
		} catch (SQLException e) {
			logger.error("初始化数据源失败", e);
		}
		return druidDataSource;
	}

	/**
	 * 动态数据源配置
	 *
	 * @return
	 */
	@Bean
	@Primary
	public DataSource multipleDataSource() {
		MultipleDataSource multipleDataSource = new MultipleDataSource();
		Map<Object, Object> targetDataSources = new HashMap<>();
		System.out.println(dsList);
		Map<String, DataSourceConfig> druid = dsList.getDruid();
		if(null != druid) {
			for (String key : druid.keySet()) {
				DruidDataSource dataSource = getDataSource(druid.get(key));
				targetDataSources.put(key, dataSource);
				multipleDataSource.setTargetDataSources(targetDataSources);
				if ("dataSource".equals(key)) {
					multipleDataSource.setDefaultTargetDataSource(dataSource);
				}

			}
		}

		//添加数据源
		multipleDataSource.setTargetDataSources(targetDataSources);
		return multipleDataSource;
	}

	@Bean("sqlSessionFactory")
	public SqlSessionFactory sqlSessionFactory() throws Exception {
		MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(multipleDataSource());

		MybatisConfiguration configuration = new MybatisConfiguration();
		configuration.setJdbcTypeForNull(JdbcType.NULL);
		configuration.setMapUnderscoreToCamelCase(true);
		configuration.setCacheEnabled(false);
		sqlSessionFactory.setConfiguration(configuration);
        sqlSessionFactory.setPlugins(new Interceptor[]{
               new MybatisPlusConfig().mybatisPlusInterceptor() //添加分页功能
        });
		return sqlSessionFactory.getObject();
	}

}
